package com.ZeroCarbon.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.ZeroCarbon.exception.FileHandingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 重复方法类
 *
 * @since 2024-11-1
 */
@Component
public class BusinessMethodUtils<T> {

    private static StringRedisTemplate redis;

    @Autowired
    public void setRedis(StringRedisTemplate redis) {
        BusinessMethodUtils.redis = redis;
    }

    /**
     * 判断值是否存在redis键中
     *
     * @return true为已点赞，false为未点赞
     */
    public static Boolean isExist(String key, String value) {
        return BooleanUtil.isTrue(redis.hasKey(key))
                && BooleanUtil.isTrue(redis.opsForSet().isMember(key, value));
    }

    /**
     * 传入类型拷贝列表
     *
     * @return 目标类型列表
     */
    public static <T> List<T> copyOriginToTargetList(List<?> originList, Class<T> target) {
        return BeanUtil.copyToList(originList, target);
    }

    /**
     * 文件列表生成集合
     *
     * @return MultipartFile列表转String列表
     */
    public static List<String> generateFilesList(String filePrefix, List<MultipartFile> filesList) {
        return filesList.stream().map(file -> {
                    try {
                        return FileHandingUtils.uploadFile(filePrefix, file);
                    } catch (FileHandingException e) {
                        throw new RuntimeException(e.toString());
                    }
                })
                .collect(Collectors.toList());
    }
}
